import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class PlaneGame extends JFrame {

    public PlaneGame() {
        setTitle("飞机大战");
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        add(new GamePanel());
        setVisible(true);
    }

    public static void main(String[] args) {
        new PlaneGame();
    }
}

class GamePanel extends JPanel implements KeyListener {
    private Player player;
    private ArrayList<Enemy> enemies;
    private ArrayList<Bullet> bullets;
    private Random random;
    private int score;
    private boolean gameOver;

    // 飞机图片资源
    private BufferedImage playerImg;
    private BufferedImage enemyImg;
    private BufferedImage bulletImg;

    public GamePanel() {
        setFocusable(true);
        addKeyListener(this);

        // 加载图片资源
        try {
            playerImg = ImageIO.read(getClass().getResource("R-C.jpg"));
            enemyImg = ImageIO.read(getClass().getResource("R-C.jpg"));
            bulletImg = ImageIO.read(getClass().getResource("R-C.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        player = new Player(375, 500);
        enemies = new ArrayList<>();
        bullets = new ArrayList<>();
        random = new Random();

        // 敌人生成定时器（加快生成速度）
        new Timer(800, e -> {
            if (!gameOver) {
                enemies.add(new Enemy(random.nextInt(750), 0));
            }
        }).start();

        // 游戏循环定时器
        new Timer(16, e -> {
            if (!gameOver) {
                update();
                repaint();
            }
        }).start();
    }

    private void update() {
        // 更新子弹
        bullets.removeIf(b -> !b.isActive());
        bullets.forEach(Bullet::move);

        // 更新敌人
        enemies.removeIf(e -> !e.isActive());
        enemies.forEach(Enemy::move);

        // 碰撞检测
        checkCollisions();
    }

    private void checkCollisions() {
        // 子弹与敌人碰撞
        bullets.forEach(b -> {
            enemies.forEach(e -> {
                if (b.getBounds().intersects(e.getBounds())) {
                    b.setActive(false);
                    e.setActive(false);
                    score += 20;
                }
            });
        });

        // 玩家与敌人碰撞
        enemies.forEach(e -> {
            if (player.getBounds().intersects(e.getBounds())) {
                player.takeDamage(1);
                e.setActive(false);
                if (player.getHealth() <= 0) {
                    gameOver = true;
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 绘制星空背景
        g.setColor(new Color(10, 10, 50));
        g.fillRect(0, 0, getWidth(), getHeight());

        // 绘制玩家
        player.draw(g);

        // 绘制敌人
        enemies.forEach(e -> e.draw(g));

        // 绘制子弹
        bullets.forEach(b -> b.draw(g));

        // 绘制游戏信息
        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑", Font.BOLD, 20));
        g.drawString("得分: " + score, 20, 40);
        g.drawString("生命值: " + player.getHealth(), 20, 70);

        if (gameOver) {
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 50));
            g.drawString("游戏结束！", 280, 300);
            g.drawString("最终得分: " + score, 290, 360);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        int speed = 7;

        if (key == KeyEvent.VK_A && player.getX() > 0) {
            player.move(-speed);
        }
        if (key == KeyEvent.VK_D && player.getX() < 750) {
            player.move(speed);
        }
        if (key == KeyEvent.VK_SPACE) {
            // 双发子弹
            bullets.add(new Bullet(player.getX() + 20, player.getY() - 30));
            bullets.add(new Bullet(player.getX() + 50, player.getY() - 30));
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}
    @Override
    public void keyReleased(KeyEvent e) {}

    class Player {
        private int x, y;
        private int health;

        public Player(int x, int y) {
            this.x = x;
            this.y = y;
            this.health = 5;
        }

        public void move(int dx) {
            x += dx;
        }

        public void takeDamage(int damage) {
            health -= damage;
        }

        public void draw(Graphics g) {
            if (playerImg != null) {
                g.drawImage(playerImg, x, y, 80, 80, null);
            } else {
                // 备用图形
                g.setColor(Color.GREEN);
                g.fillRect(x, y, 80, 80);
            }
        }

        public Rectangle getBounds() {
            return new Rectangle(x + 15, y + 15, 50, 50);
        }

        public int getX() { return x; }
        public int getY() { return y; }
        public int getHealth() { return health; }
    }

    class Enemy {
        private int x, y;
        private boolean active;

        public Enemy(int x, int y) {
            this.x = x;
            this.y = y;
            this.active = true;
        }

        public void move() {
            y += 4;
            if (y > 600) active = false;
        }

        public void draw(Graphics g) {
            if (enemyImg != null) {
                g.drawImage(enemyImg, x, y, 60, 60, null);
            } else {
                g.setColor(Color.RED);
                g.fillRect(x, y, 60, 60);
            }
        }

        public Rectangle getBounds() {
            return new Rectangle(x + 10, y + 10, 40, 40);
        }

        public boolean isActive() { return active; }
        public void setActive(boolean active) { this.active = active; }
    }

    class Bullet {
        private int x, y;
        private boolean active;

        public Bullet(int x, int y) {
            this.x = x;
            this.y = y;
            this.active = true;
        }

        public void move() {
            y -= 8;
            if (y < 0) active = false;
        }

        public void draw(Graphics g) {
            if (bulletImg != null) {
                g.drawImage(bulletImg, x, y, 10, 20, null);
            } else {
                g.setColor(Color.YELLOW);
                g.fillRect(x, y, 5, 15);
            }
        }

        public Rectangle getBounds() {
            return new Rectangle(x, y, 5, 15);
        }

        public boolean isActive() { return active; }
        public void setActive(boolean active) { this.active = active; }
    }
}